package cn.tedu.mvc.controller;

import cn.tedu.mvc.entity.User;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/test")
    @ResponseStatus(HttpStatus.CREATED)
    public String test(){
        return "Hello!";
    }
    //创建一个图片数据
    private byte[] image(String message){
        try {
            BufferedImage img = new BufferedImage(100, 60,
                    BufferedImage.TYPE_3BYTE_BGR);
            Graphics2D g = img.createGraphics();
            g.setColor(Color.WHITE);
            g.drawString(message, 10, 50);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(img, "png", out);
            out.close();
            return out.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

    // 图片下载
    // /demo/image
    @GetMapping("/image/{message}")
    public ResponseEntity<byte[]> getImage(@PathVariable String message) throws UnsupportedEncodingException {
        byte[] bytes = image(message);
        String filename = URLEncoder.encode("图片.png", "UTF-8");
        ResponseEntity<byte[]> responseEntity = ResponseEntity.status(200)
                        .contentType(MediaType.IMAGE_PNG)
                        .contentLength(bytes.length)
                        .header("Content-Disposition",
                                "attachment; filename=\""+filename+"\"")
                        .body(bytes);
        return responseEntity;
    }

    @PutMapping("/users/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public String updateUser(@PathVariable Integer id,
                             @RequestBody User user,
                             @RequestHeader("Content-Type") String contentType){
        System.out.println(id);
        System.out.println(user);
        System.out.println(contentType);
        return "OK";
    }

}
